package com.chentianyu.learn.javalinkmysql;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(name = "updateUser",value = "/update-user")
public class updateServlet extends HttpServlet {
    String url = "jdbc:mysql://localhost:3306/java_accout";
    String sqlusername = "root";
    String sqlpassword = "1234567890";

    public void init(){}

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("username");
        String newPassword = request.getParameter("newPassword");
        String sql = "update users set password=? where username=?";

        try {
            Connection connection = DriverManager.getConnection(url, sqlusername, sqlpassword);
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1,newPassword);
            stmt.setString(2,name);

            int result = stmt.executeUpdate();
            PrintWriter out = response.getWriter();

            out.println(result);


        }catch (SQLException e){
            e.printStackTrace();
        }

    }
}
